import Express from 'express'
// 1. 创建路由对象 Express.Router
import {checkOldPass, loginService, registerService,updatePass,updateUserServ} from "../Service/userService.js"
import {checkAuth} from "../Middleware/checkAuth.js"
import {findUserDao} from "../Dao/userDao.js"
export const UserRouter = Express.Router()

UserRouter.post('/login', async (req, res) => {
    const body  = req.body;
    console.log("body",body);
    
    if(body?.code.toUpperCase() === req.session?.code.toUpperCase()){
        //验证码OK  
        //查数据库
        const json = await loginService(body)
        res.json(json)
    }else{
        res.json({
            code:1,
            msg:"验证码错误"
        })
    }
    
})

UserRouter.post('/register', async (req, res) => {
    const {username,nickname,code} = req.body;
    console.log("req.session?.code?:",req.session?.code);
    console.log("code:",code);

    if(code?.toUpperCase() === req.session?.code?.toUpperCase()){
        await registerService({username,nickname})
        res.json({
            code:0,
            msg:"注册成功"
        })
    }else{
        //验证码没通过
        res.json({
            code:1,
            msg:"验证码错误"
        })
    }
})

UserRouter.get("/womai",checkAuth,async (req,res)=>{
    
    console.log("username",req.username);
    const user = await findUserDao(req.username);
    console.log("user",user);
    
    res.json({
        code:0,
        msg:"ok",
        data:user
    })
})

UserRouter.post("/checkOldPass",checkAuth,async(req,res)=>{
    const {username,oldpass} = req.body;
    if(req.username === username){
        const result = await checkOldPass({username,oldpass})
        
        if(result){
            //与原密码相等
            res.json({
                code:0,
                msg:"密码正确"
            })
        }else{
            res.json({
                code:1,
                msg:"密码不正确"
            })
        }
    }else{
        res.json({
            code:1,
            msg:"与当前用户名不一致",
        })
    }
})

UserRouter.post("/updatePass",async(req,res)=>{
    const user = await updatePass(req.body)
    if(user != null){
        res.json({
            code:0,
            msg:"修改密码成功",
            data:user
        })
    }else{
        res.json({
            code:1,
            msg:"更新失败"
        })
    }
})
UserRouter.put("/:id",async(req,res)=>{
    const id = req.params.id;
    const body = req.body;
    const result = await updateUserServ(id,body);
    res.json(result)
})